package com.qiumo.gmtool.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiumo.gmtool.common.RetResult;
import com.qiumo.gmtool.entity.ScoreDataEntity;
import com.qiumo.gmtool.entity.SignDataEntity;
import com.qiumo.gmtool.entity.UserEntity;
import com.qiumo.gmtool.mail.MailParams;
import com.qiumo.gmtool.mail.MailUtil;
import com.qiumo.gmtool.mapper.ScoreDataMapper;
import com.qiumo.gmtool.mapper.SignDataMapper;
import com.qiumo.gmtool.mapper.UserMapper;
import com.qiumo.gmtool.service.SignDataService;
import com.qiumo.gmtool.utils.FileUtils;
import java.util.Date;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@RequiredArgsConstructor
public class SignDataServiceImpl extends ServiceImpl<SignDataMapper, SignDataEntity> implements SignDataService {

    @Value("${genshin.keyPath}")
    public String keyPath;

    private final SignDataMapper signDataMapper;

    private final ScoreDataMapper scoreDataMapper;

    private final UserMapper userMapper;

    private final MailUtil mailUtil;


    @Override
    public RetResult getListByMonth() {
        //获取日期
        Date date = DateUtil.date();
        String format = DateUtil.format(date, "yyyyMM");
        //获取本月签到配置
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            array = FileUtils.readJsonArray(keyPath + "/sign/" + format + ".json");
            if (array.isEmpty() || ObjectUtil.isEmpty(array)) {
                return RetResult.err("未配置有效奖励");
            }
            json.put("list", array);
        } catch (Exception e) {
            return RetResult.err("未配置签到奖励，或配置有误");
        }
        //查询本月签到情况
        Integer total = signDataMapper.getMonthSignCountByUid(StpUtil.getLoginId());
        json.put("total", total);
        //查询今日是否签到
        Integer today = signDataMapper.getTodaySignByUid(StpUtil.getLoginId());
        json.put("today", today);
        return RetResult.succ(json);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public RetResult sign() {
        //当前登录人ID
        String id = StpUtil.getLoginIdAsString();
        //获取日期
        Date date = DateUtil.date();
        String format = DateUtil.format(date, "yyyyMM");
        //查询今日是否签到
        Integer today = signDataMapper.getTodaySignByUid(StpUtil.getLoginId());
        if (today >= 1) {
            return RetResult.err("衰仔，你今天签到过辣");
        }
        //获取本月签到配置
        JSONArray array = new JSONArray();
        try {
            array = FileUtils.readJsonArray(keyPath + "/sign/" + format + ".json");
            if (array.isEmpty() || ObjectUtil.isEmpty(array)) {
                return RetResult.err("未配置有效奖励");
            }
        } catch (Exception e) {
            return RetResult.err("未配置签到奖励，或配置有误");
        }
        //查询本月签到情况
        Integer total = signDataMapper.getMonthSignCountByUid(StpUtil.getLoginId());
        JSONObject item = array.getJSONObject(total);
        //添加记录到数据库
        SignDataEntity entity = new SignDataEntity();
        entity.setUid(String.valueOf(StpUtil.getLoginId()));
        entity.setItemId(item.getString("id"));
        entity.setItemNum(item.getString("num"));
        entity.setItemName(item.getString("name"));
        entity.setImgUrl(item.getString("img"));
        signDataMapper.insert(entity);
        //随机获取 1 - 20 积分，并保存记录
        int randomNumber = RandomUtil.randomInt(1, 21);
        ScoreDataEntity scoreDataEntity = new ScoreDataEntity();
        scoreDataEntity.setUid(id);
        scoreDataEntity.setScore(randomNumber);
        scoreDataEntity.setScoreType("0");
        scoreDataEntity.setReason("每日签到");
        scoreDataMapper.insert(scoreDataEntity);
        //修改用户积分
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
            .eq(UserEntity::getUid, id));
        userEntity.setScore(userEntity.getScore() + randomNumber);
        userMapper.update(userEntity, new LambdaQueryWrapper<UserEntity>()
            .eq(UserEntity::getUid, id));
        //发送物品
        MailParams params = new MailParams();
        params.setUid(String.valueOf(StpUtil.getLoginId()));
        //标题
        params.setTitle("⌈云深不知处⌋每日签到活动");
        //内容
        params.setContent(
            "亲爱的旅行者：\n云深不知处每日签到奖品现已发放，请在附件中查收\n本次签到额外获得" + randomNumber
                + "积分\n感谢旅行者对于云深不知处的关注和支持。");
        params.setItem_list(item.getString("id") + ":" + item.getString("num"));
        RetResult retResult = mailUtil.sendMail(params);
        if (String.valueOf(retResult.get("code")).equals("500")) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RetResult.err("签到失败了，联系管理员！！！");
        } else {
            RetResult succ = RetResult.succ(item);
            succ.put("score", randomNumber);
            return succ;
        }
    }
}
